/**
 * Created by Xiaobing on 2016/6/28.
 */

function Topology() {
    var celllayer = gis_core.addGraphicsLayer("Topology_cell_layer", "小区图层");
    var alarmlayer = gis_core.addGraphicsLayer("Topology_alarm_layer", "告警小区标记");
    var marklayer = gis_core.addGraphicsLayer("Topology_mark_layer", "小区定位");
    var cellLightlayer = gis_core.addGraphicsLayer("Topology_cellLight_layer", "小区高亮");
    var cellLayer_click_handle = null;
    var delta_temp = null;
    var time = null;
    var roomId = null;
    var ids = null;
    var region = {
        id: 1,
        type: 9000
    };
    var eci = "";

    //地图改变事件
    var extentchange = function (delta) {
        delta_temp = delta;
        getTopolLTEBts();
    };

    var getMachineRoom = function (callback) {
        var key = "topology_machinerooms";
        var data = gis_resources.getCache(key);
        if (data == null) {
            $.ajax({
                url: "/getmachineroom",
                dataType: "json",
                async: true,
                type: "GET",
                beforeSend: function () {
                    gis_common.isLoadingAddCount();
                },
                success: function (req) {
                    gis_common.outPut(req, function (rooms) {
                        gis_resources.addCache("topology_machinerooms", rooms);
                        callback(rooms);
                    });
                },
                complete: function () {
                    gis_common.isLoadingSunCount();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
                }
            });
        }
        else {
            return callback(data);
        }
    };
    var loadCityPreDetail = function () {
        $.ajax({
            url: "/gettopcitypre",
            dataType: "json",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId,
                ids:ids
            },
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    createCityPreDetailHtml(data);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var createCityPreDetailHtml = function (list) {
        var content = "<table id='topology_createCityPreDetail_table' class='table' style='width:400px;margin-top:5px;margin-right:10px'>";
        content += "	<tbody>";
        for (var i = 0; i < list.length; i++) {
            var l = list[i];
            content += "<tr class='change'>";
            content += "<td>" + l.name + "</td>";
            if ((l.id == "colse_cell_cnt" || l.id == "is_alarm" || l.id == "ft_bad_cnt" || l.id == "bad_attach_cell_rat" || l.id == "bad_eps_cell_rat") && l.currentValue != "0"&&l.currentValue != "0.0%") {
                content += "<td><a href='javascrip:void(0);' title='点击查看小区明细' style='color: blue' typ='" + l.id + "'>" + l.currentValue + "</a></td>";
            }
            else {
                content += "<td>" + l.currentValue + "</td>";
            }
            content += "<td>" + l.contrastValue + "</td>";
            content += "<td>" + l.rate + "</td>";
            content += "</tr>";
        }
        content += "	</tbody>";
        content += "</table>";
        var div = $(content);
        gis_layout.createLeftWidget("Topology_createCityPreDetailHtml", "地市", div);
        div.find("a").bind("click", function () {
            var $obj = $(this);
            var typ = $obj.attr("typ");
            getSerialWeakGridTable(typ);
        });
    };
    var getSerialWeakGridTable = function (typ) {
        var content = "<div>";
        content += "<table id='Topology_Grid_Table'></table>";
        content += "<div id='Topology_Grid_Table_Pager'></div>"
        content += "<div>";
        var div = $(content);

        gis_layout.createLeftWidget("Topology_Grid_Table_JQGrid_Div", "小区列表", div);
        div.find("#Topology_Grid_Table").jqGrid({
            url: '/gettololltecelltype?time=' + time + "&cityid=" + region.id + "&roomid=" + roomId + "&type=" + typ,
            datatype: "json",
            width: 400,
            colNames: ['ID', '小区名称', 'TAC', 'ECI', '地市', '机房', "longitude", "latitude"],
            colModel: [{
                name: 'id',
                index: 'id',
                width: 0,
                hidden: true
            }, {
                name: 'name',
                index: 'name',
                width: 100
            }, {
                name: 'tac',
                index: 'tac',
                width: 30
            }, {
                name: 'eci',
                index: 'eci',
                width: 30,
                align: "right"
            }, {
                name: 'cityName',
                index: 'cityName',
                width: 40,
                align: "right"
            }, {
                name: 'roomName',
                index: 'roomName',
                width: 40,
                align: "right"
            }, {
                name: 'longitude',
                index: 'longitude',
                width: 0,
                hidden: true
            }, {
                name: 'latitude',
                index: 'latitude',
                width: 0,
                hidden: true
            }
            ],
            rowNum: 10,
            rowList: [10, 20, 30, 50],
            pager: '#Topology_Grid_Table_Pager',
            mtype: "get",
            viewrecords: true,
            caption: "",
            onSelectRow: function (id) {
                marklayer.clear();
                var data = div.find("#Topology_Grid_Table").jqGrid('getRowData', id);
                eci = data.eci;
                var longitude = data.longitude;
                var latitude = data.latitude;
                gis_common.setExtent(longitude * 1.0 + 0.003, latitude * 1.0 + 0.003, longitude * 1.0 - 0.003, latitude * 1.0 - 0.003);
                loadCellClose(eci);
                loadCellWarn(eci);
                loadCellKpiDetail(eci);
            }
        });
    };

    var getTopolLTEBts = function () {
        celllayer.clear();
        alarmlayer.clear();
        $.ajax({
            url: "/gettopolltebts",
            dataType: "json",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId,
                extent: JSON.stringify(gis_common.getMapExtent())
            },
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (bts) {
                    createCellGraphic(bts);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var createCellGraphic = function (bts) {
        if (bts == null || bts.length == 0) {
            return;
        }
        var graphics = gis_common.createCellCover(bts, 50);
        graphics = graphics.reverse();
        for (var j = 0; j < graphics.length; j++) {
            var g = graphics[j];
            var cell = g.attributes.data;
            if (cell.tag != "cluster") {
                var symbol = new esri.symbol.SimpleFillSymbol();
                if (cell.quality == "3" || cell.isAttach =="1" || cell.isEps =="1") {
                    symbol.setColor(new esri.Color([255, 40, 75, 1]));
                    symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([255, 40, 75, 0.8]), 1));
                } else if (cell.quality == "2") {
                    symbol.setColor(new esri.Color([255, 255, 75, 1]));
                    symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([151, 151, 151, 0.8]), 1));
                }
                else {
                    symbol.setColor(new esri.Color([40, 255, 75, 1]));
                    symbol.setOutline(new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([151, 151, 151, 0.8]), 1));
                }
                g.setSymbol(symbol);

                var length = parseInt(g.geometry.rings[0].length / 2);
                var p = g.geometry.rings[0][length];
                if (p != null && p != undefined && cell.isAlarm == "1") {
                    var point = new esri.geometry.Point(p[0], p[1], gis_core.map.spatialReference);
                    var symbol_alarm = new esri.symbol.PictureMarkerSymbol('/images/alarm.png', 23, 23);
                    var graphic = new esri.Graphic(point, symbol_alarm);
                    alarmlayer.add(graphic);
                }
                if (cell.eci == eci) {
                    var longitude = cell.longitude;
                    var latitude = cell.latitude;
                    var lon = longitude - (longitude - p[0]) / 2;
                    var lat = latitude - (latitude - p[1]) / 2;

                    var point = new esri.geometry.Point(lon, lat, gis_core.map.spatialReference);
                    var symbol = new esri.symbol.PictureMarkerSymbol('/images/point-green.png', 28, 28);
                    var graphic = new esri.Graphic(point, symbol);
                    marklayer.add(graphic);
                    //marklayer
                }
            }
            celllayer.add(g);
        }
    }
    var loadSerialWeakGridData = function (typ) {
        $.ajax({
            url: "/gettololltecelltype",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId,
                type: typ
            },
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (data) {
                    if (data > 0) {
                        getSerialWeakGridTable();
                    } else {
                        gis_common.showMessage("无数据");
                        gis_layout.removeLeftWidget("Topology_Grid_Table_JQGrid_Div");
                    }
                });
            },
            complete: function (lines) {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };
    var loadCellKpiDetail = function (eci) {
        $.ajax({
            url: "/getpopolltecelldetail",
            dataType: "json",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId,
                eci: eci
            },
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (kpi) {
                    var div = gis_common.createKeyValueList(kpi);
                    gis_layout.createRightWidget("Topology_loadCellKpiDetail", "小区指标明细", div);
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var loadCellWarn = function (eci) {
        $.ajax({
            url: "/getpopolltecellwarn",
            dataType: "json",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId,
                eci: eci
            },
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (kpi) {
                    if(kpi.length>0){
                        var div = gis_common.createKeyValueList(kpi);
                        gis_layout.createRightWidget("Topology_loadCellWarn", "小区告警", div);
                    }else{
                        gis_layout.removeRightWidget("Topology_loadCellWarn");
                    }

                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };

    var loadCellClose = function (eci) {
        $.ajax({
            url: "/getpopolltecellclose",
            dataType: "json",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId,
                eci: eci
            },
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (kpi) {
                    if(kpi.length>0) {
                        var div = gis_common.createKeyValueList(kpi);
                        gis_layout.createRightWidget("Topology_loadCellClose", "小区闭站", div);
                    }else{
                        gis_layout.removeRightWidget("Topology_loadCellClose");
                    }
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    };



    var setCellLight = function (g) {
        var rings = g.geometry.rings;
        var rings = [];
    };

    var initLegend = function () {
        var content = "";
        content += "<div class=\"legend-box\" style=\"background:rgba(40,255,75,0.5);color:#fff;\">质优</div>";
        content += "<div class=\"legend-box\" style=\"background:rgba(255,255,75,0.5);color:#fff;\">质中</div>";
        content += "<div class=\"legend-box\" style=\"background:rgba(255,40,75,0.5);color:#fff;\">质差</div>";
        content += "<div class=\"legend-box\">告警<img src=\"/images/alarm.png\"/></div>";
        var div = $(content);
        gis_layout.createLegend("Topology_legend", "图例", div);
    };
    var getTopolLTECellExtent = function () {
        $.ajax({
            url: "/gettopolltecellextent",
            dataType: "json",
            data: {
                time: time,
                cityid: region.id,
                roomid: roomId
            },
            async: true,
            type: "GET",
            beforeSend: function () {
                gis_common.isLoadingAddCount();
            },
            success: function (req) {
                gis_common.outPut(req, function (extent) {
                    if (extent.xMax != 0 && extent.yMax != 0) {
                        gis_common.setExtent(extent.xMax, extent.yMax, extent.xMin, extent.yMin);
                    }
                    getTopolLTEBts();
                });
            },
            complete: function () {
                gis_common.isLoadingSunCount();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                gis_common.showError(XMLHttpRequest.status + " " + XMLHttpRequest.readyState + " " + textStatus);
            }
        });
    }
    this.initQuery = function (t, c, r,ids) {
        time = t;
        roomId = r;
        region.id = c;
        region.type = 9001;
        ids = ids;

        celllayer.clear();
        alarmlayer.clear();
        marklayer.clear();

        loadCityPreDetail();
        getTopolLTECellExtent();
    };
    /**
     * 查询表格
     * @param callback
     */
    this.createQuryParamHtml = function (callback) {
        gis_resources.getRegions(function (regions) {
            getMachineRoom(function (rooms) {
                var content = "<div class=\"form-group\">";
                content += "	<label class='col-sm-3 control-label'>查询时间:</label>";
                content += "	<div id='res_type' class='col-sm-9'>";
                content += "			<input id='topology_param_time' type='text' class='form-control' onFocus=\"WdatePicker({lang:'zh-cn',dateFmt:'yyyy-MM-dd HH'});\"/>";
                content += " 	</div > ";
                content += " </div > ";

                content += "<div class='form-group'>";
                content += "	<label for='' class='col-sm-3 control-label'>地市:</label>";
                content += " 	<div class='col-sm-9'>";
                content += "		<select id='topology_region_select' class='form-control'>";
                if (regions != null && regions != undefined && regions.length > 0) {
                    for (var i = 0; i < regions.length; i++) {
                        var r = regions[i];
                        if (r.type != 9000) {
                            content += "<option neid='" + r.id + "' netype='" + r.type + "'>" + r.name + "</option>";
                        }
                    }
                }
                content += "		</select>";
                content += "	</div>";
                content += "</div>";

                content += "<div class='form-group'>";
                content += "	<label for='' class='col-sm-3 control-label'>机房:</label>";
                content += " 	<div class='col-sm-9'>";
                content += "		<select id='topology_param_rooms_select' class='form-control'>";
                if (rooms != null && rooms != undefined && rooms.length > 0) {
                    for (var i = 0; i < rooms.length; i++) {
                        var r = rooms[i];
                        content += "<option roomid='" + r.id + "'>" + r.name + "</option>";
                    }
                }
                content += "		</select>";
                content += "	</div>";
                content += "</div>";

                content += "<div class='form-group'>";
                content += " 	<div class='col-sm-9 col-sm-offset-3'>";
                content += "		<button id='topology_param_btn_load' class='btn btn-primary'>确 定</button>";
                content += "	</div>";
                content += "</div>";

                var div = $(content);
                div.find("#topology_param_btn_load").bind("click", function () {
                    //时间
                    time = div.find("#topology_param_time").val().replace(/-/g, '').replace(/ /g, '');
                    if (gis_common.stringIsNullOrWhiteSpace(time)) {
                        gis_common.showMessage("请选择时间");
                        div.find("#topology_param_time").focus();
                        return;
                    }
                    //地市
                    var selects = div.find("#topology_region_select option:selected");
                    if (selects != null && selects != undefined) {
                        region.id = selects.attr("neid");
                        region.type = selects.attr("netype");
                    } else {
                        gis_common.showMessage("请选择地市");
                        div.find("#topology_region_select").focus();
                        return;
                    }
                    //机房
                    var rs = div.find("#topology_param_rooms_select option:selected");
                    if (rs != null && rs != undefined) {
                        roomId = rs.attr("roomid");
                    } else {
                        gis_common.showMessage("请选择机房");
                        div.find("#topology_param_rooms_select").focus();
                        return;
                    }
                    marklayer.clear();
                    loadCityPreDetail();
                    getTopolLTECellExtent();
                });
                callback(div);
            })
        });
    }
    /**
     * 初始化
     */
    this.init = function () {
        gis_core.addExtentChange("Topology", extentchange);
        //注册模块
        gis_core.addPlugin(this);
        initLegend();
        if (cellLayer_click_handle != null) {
            dojo.disconnect(cellLayer_click_handle);
        }
        cellLayer_click_handle = celllayer.on("click", function (evt) {
            var cell = evt.graphic.attributes.data;
            loadCellClose(cell.eci);
            loadCellWarn(cell.eci);
            loadCellKpiDetail(cell.eci);
            setCellLight(evt.graphic);
        });

    };
    /**
     * 销毁
     */
    this.destroy = function () {
        gis_core.removeExtentChange("Topology");
    };
    /**
     * 模块信息
     * @type {{id: string, name: string}}
     */
    this.title = {
        id: "00_03_00",
        name: "拓扑GIS"
    };
}

var topology = null;

function initTopology() {
    if (topology == null) {
        topology = new Topology();
    }
    topology.init();
}

function topology_createQuryParamHtml(obj) {
    initTopology();
    gis_layout.createMenubarWithFun("topology_createQuryParamHtml", obj, "无线拓扑", topology.createQuryParamHtml);
}

function topology_init_query() {
    var time = gis_common.getQueryString("time")
    var cityid = gis_common.getQueryString("cityid");
    var roomid = gis_common.getQueryString("roomid");
    var ids = gis_common.getQueryString("ids");
    if (!gis_common.stringIsNullOrWhiteSpace(time) && !gis_common.stringIsNullOrWhiteSpace(cityid) && !gis_common.stringIsNullOrWhiteSpace(roomid)&& !gis_common.stringIsNullOrWhiteSpace(ids)) {
        initTopology();
        topology.initQuery(time, cityid, roomid,ids)
    }
}